<template>
  <div class="AcceptAndHearACase" v-loading="loading">
    <el-form :inline="true" :model="searchData">
      <el-form-item label="租客：">
        <el-input
          v-model="searchData.userName"
          placeholder="请输入租客姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="租赁状态：">
        <el-select v-model="searchData.status" placeholder="请选择租赁状态">
          <el-option label="已到期" :value="0"></el-option>
          <el-option label="出租中" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="serach"
          class="btn-search"
          >筛选</el-button
        >
        <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="newBuilt"
      class="btn-export"
      >添加租赁信息</el-button
    >
    <el-table
      :data="tableData"
      style="width: 100%"
      height="84%"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" align="center">
      </el-table-column>
      <el-table-column label="合同" align="center" prop="contractImg">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img
              :src="scope.row.contractImg"
              style="width: 150px; height: 150px"
            />
            <img
              slot="reference"
              :src="scope.row.contractImg"
              style="max-height: 80px; max-width: 80px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="tenantName" label="租客" align="center">
      </el-table-column>
      <el-table-column prop="houseName" label="房源名字" align="center">
      </el-table-column>
      <el-table-column prop="address" label="地址" align="center" width="500">
      </el-table-column>
      <el-table-column prop="leaseTime" label="租赁时间" align="center">
      </el-table-column>
      <el-table-column prop="leaseState" label="租赁状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.leaseState ? "出租中" : "已到期" }}
        </template>
      </el-table-column>
      <el-table-column prop="payAmount" label="缴费金额" align="center">
      </el-table-column>
      <el-table-column prop="rentState" label="租金状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.rentState ? "已缴费" : "未缴费" }}
        </template>
      </el-table-column>
      <el-table-column prop="payableTime" label="应缴费时间" align="center">
      </el-table-column>
      <el-table-column prop="paidInTime" label="实缴费时间" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.row)"
            type="text"
            size="medium"
            style="margin-right: 10px"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @confirm="deleteConfirm(scope.row)"
          >
            <el-button
              slot="reference"
              type="text"
              size="medium"
              style="color: red"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="AcceptAndHearACase-content-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="isNew ? '添加' : '编辑'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      v-loading="loading"
    >
      <el-form
        :model="formData"
        label-width="100px"
        :rules="formRules"
        ref="form"
      >
        <el-form-item label="上传合同：" prop="contractImg">
          <el-upload
            class="avatar-uploader"
            action="http://43.139.235.169:8081/cos/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.contractImg"
              :src="formData.contractImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="房源名字：" prop="houseName">
          <el-select
            v-model="formData.houseName"
            placeholder="请选择房源"
            @change="houseChange"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in houseList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input
            v-model="formData.address"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="租客：" prop="tenantName">
          <el-select
            v-model="formData.tenantName"
            placeholder="请选择用户"
            @change="tenantChange"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in userList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租赁时间：" prop="leaseTime">
          <el-input
            v-model="formData.leaseTime"
            placeholder="请输入租赁时间"
          ></el-input>
        </el-form-item>
        <el-form-item label="租赁状态" prop="leaseState">
          <el-radio-group v-model="formData.leaseState">
            <el-radio :label="0">未出租</el-radio>
            <el-radio :label="1">已出租</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="缴费金额：" prop="payAmount">
          <el-input
            v-model="formData.payAmount"
            placeholder="请输入缴费金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="租金状态" prop="rentState">
          <el-radio-group v-model="formData.rentState">
            <el-radio :label="0">未缴费</el-radio>
            <el-radio :label="1">已缴费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="应缴费时间：" prop="payableTime">
          <el-date-picker
            v-model="formData.payableTime"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择应缴费时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实缴费时间：" prop="paidInTime">
          <el-date-picker
            v-model="formData.paidInTime"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择实缴费时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Housing",
  data() {
    const validateLeaseState = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择租赁状态"));
      } else {
        callback();
      }
    };
    const validateRentState = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择租金状态"));
      } else {
        callback();
      }
    };
    return {
      //加载状态
      loading: false,
      //分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchData: {
        userName: "",
        status: "",
      },
      tableData: [],
      houseList: [],
      userList: [],
      dialogVisible: false,
      formData: {},
      isNew: false,
      //弹窗校验规则
      formRules: {
        contractImg: [
          { required: true, trigger: "blur", message: "请上传房源图片" },
        ],
        houseName: [
          { required: true, trigger: "blur", message: "请选择房源名字" },
        ],
        address: [{ required: true, trigger: "blur", message: "请输入地址" }],
        tenantName: [
          { required: true, trigger: "blur", message: "请选择用户" },
        ],
        leaseTime: [
          { required: true, trigger: "blur", message: "请输入租赁时间" },
        ],
        leaseState: [
          { required: true, trigger: "blur", validator: validateLeaseState },
        ],
        payAmount: [
          { required: true, trigger: "blur", message: "请输入缴费金额" },
        ],
        rentState: [
          { required: true, trigger: "blur", validator: validateRentState },
        ],
        payableTime: [
          { required: true, trigger: "blur", message: "请选择应缴费时间" },
        ],
        payableTime: [
          { required: true, trigger: "blur", message: "请选择实缴费时间" },
        ],
      },
    };
  },
  mounted() {
    this.getLeasingInformationList();
    this.userListPaging();
    this.getHousingResourcesInfoList();
  },
  methods: {
    //房源改变获取id
    houseChange(e) {
      // console.log(e);
      this.houseList.forEach((el) => {
        if (el.id == e) {
          this.formData.houseName = el.name;
          this.formData.houseId = el.id;
        }
      });
    },
    //用户改变获取id
    tenantChange(e) {
      this.userList.forEach((el) => {
        if (el.id == e) {
          this.formData.houseName = el.name;
          this.formData.houseId = el.id;
        }
      });
    },
    //获取房源数据
    async getHousingResourcesInfoList() {
      const res = await this.$api.getHousingResourcesInfoList({
        pageIndex: -1,
        pageSize: -1,
      });
      // console.log(res, "房源");
      this.houseList = res.data.records;
    },
    //获取用户数据
    async userListPaging() {
      const res = await this.$api.userListPaging({
        pageIndex: -1,
        pageSize: -1,
      });
      // console.log(res.data, "用户");
      this.userList = res.data.records;
    },
    //获取数据
    async getLeasingInformationList(tenantName, leaseState) {
      this.loading = true;
      const res = await this.$api.getLeasingInformationList({
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        tenantName: tenantName, //租客名字
        leaseState: leaseState, //租赁状态
      });
      // console.log(res);
      this.tableData = res.data.records;
      this.total = res.data.total;
      this.loading = false;
    },
    //查询数据
    serach() {
      this.getLeasingInformationList(
        this.searchData.userName,
        this.searchData.status
      );
    },
    //重置按钮
    reset() {
      this.searchData = {
        userName: "",
        status: "",
      };
      this.getLeasingInformationList();
    },
    //新建
    newBuilt() {
      this.formData = {
        deviceImg: "",
      };
      this.isNew = true;
      this.dialogVisible = true;
    },
    //编辑
    handleClick(row) {
      // console.log(row);
      this.formData = row;
      this.isNew = false;
      this.dialogVisible = true;
    },
    //编辑或者新建弹窗确认
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.isNew) {
            //新建
            this.$api.addLeasingInformation(this.formData).then((res) => {
              if (res.code === 0) {
                this.loading = false;
                this.dialogVisible = false;
                this.reset();
                this.$message({
                  message: "添加成功！",
                  type: "success",
                });
              }
            });
          } else {
            //编辑
            this.$api.updateLeasingInformation(this.formData).then((res) => {
              // console.log(res);
              if (res.code === 0) {
                this.loading = false;
                this.dialogVisible = false;
                this.reset();
                this.$message({
                  message: "修改成功！",
                  type: "success",
                });
              }
            });
          }
        } else {
          this.$message({
            message: "请输入完整内容",
            type: "error",
          });
          return;
        }
      });
    },
    //关闭弹窗的方法
    handleClose() {
      this.dialogVisible = false;
    },
    //删除
    async deleteConfirm(row) {
      const res = await this.$api.deleteLeasingInformationById({
        id: row.id,
      });
      if (res.code === 0) {
        this.serach();
        this.$message({
          message: "删除成功！",
          type: "success",
        });
      }
    },
    //上传成功
    handleAvatarSuccess(res, file) {
      this.formData.contractImg = res.resultObj;
      this.loading = false;
      //移除图片表单校验结果
      this.$refs.form.clearValidate("contractImg");
    },
    //上传前
    beforeAvatarUpload(file) {
      this.loading = true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      this.loading = isJPG && isLt2M;
      return isJPG && isLt2M;
    },
    //页数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      let that = this;
      that.pageSize = val;
      that.serach();
    },
    //翻页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let that = this;
      that.currentPage = val;
      that.serach();
    },
  },
};
</script>

<style lang="scss" scoped>
.btn-search {
  background: #409eff;
  border: 1px solid #409eff;
  &:hover {
    opacity: 0.8;
  }
}
.btn-export {
  width: 150px;
  background: #409eff;
  border: 1px solid #409eff;
  margin-bottom: 20px;
  &:hover {
    opacity: 0.8;
  }
}
.avatar-uploader ::v-deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep(.el-upload):hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.AcceptAndHearACase {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  border-radius: 4px;
  padding: 24px;
  overflow: hidden;

  &-content {
    width: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &-table {
      width: 100%;
      flex: 1;
      overflow-y: auto;
    }
    &-page {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      margin-top: 16px;
      .el-pagination {
        padding: 0;
        .el-pagination__total {
          line-height: 40px;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
}
</style>

